﻿using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Quartz;
using Quartz.Impl;

namespace QuartzScheduler;

public class QuartzTimerFactory
{
    private const string ActionName = "Action";
    private static readonly Lazy<StdSchedulerFactory> Factory = new();

    public static async Task<QuartzTimer> CreateSchedulerAsync(string cron, Action action)
    {
        var job = JobBuilder.Create<Person1>()
            .Build();
        job.JobDataMap.TryAdd(ActionName, action);
        var trigger = TriggerBuilder.Create().WithCronSchedule(cron)
            .Build();
        var scheduler = await Factory.Value.GetScheduler();
        await scheduler.Start();
        await scheduler.ScheduleJob(job, trigger);
        return new QuartzTimer(action, scheduler);
    }

    [DisallowConcurrentExecution] //禁止并发执行
    private class Person1 : IJob
    {
        public async Task Execute(IJobExecutionContext context)
        {
            if (context.JobDetail.JobDataMap.Get(ActionName) is Action funAction) funAction();

            await Task.CompletedTask;
        }
    }
}

public class QuartzTimer
{
    private readonly Action _action;
    private readonly IScheduler _scheduler;

    internal QuartzTimer(Action action, IScheduler scheduler)
    {
        _action = action;
        _scheduler = scheduler;
    }

    public void Run()
    {
        _action();
    }


    public void Shutdown()
    {
        _scheduler.Shutdown(true);
    }
}